<template>
<el-dialog :visible.sync="visible" :title="title" v-if="visible">
  <el-form :model="formData" label-position="right" label-width="80px" :rules="rules" ref="formData">
    <el-form-item label="章节名称" prop="catalogName">
      <el-input placeholder="请输入章节名称" v-model="formData.catalogName">
      </el-input>
    </el-form-item>
    <el-form-item label="章节内容">
      <vue-editor ref="vueEditor" v-model="formData.content"/>
    </el-form-item>
    <el-form-item label="发表状态">
      <el-radio-group v-model="formData.catalogStatus">
        <el-radio :label="1">发表</el-radio>
        <el-radio :label="2">草稿</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item v-if="formData.catalogStatus === 1" label="发表时间">
      <el-date-picker type="datetime" v-model="formData.applyTime" placeholder="发表时间">
      </el-date-picker>
    </el-form-item>
    <el-form-item label="状态">
      <el-radio-group v-model="formData.status">
        <el-radio :label="1">可用</el-radio>
        <el-radio :label="2">禁用</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="update">提交</el-button>
      <el-button type="warning" @click="visible = false">取消</el-button>
    </el-form-item>
  </el-form>
  <div class="ql-container ql-snow">
    <div class="ql-editor" v-html="formData.content"></div>
  </div>
</el-dialog>
</template>

<script>
const formData = {
  id: '',
  content: '',
  catalogStatus: 1,
  catalogName: '',
  status: 1,
  applyTime: '',
  bookId: ''
}
export default {
  name: 'CatalogUpdate',
  data () {
    return {
      visible: false,
      title: '添加数据',
      formData: {
        ...formData
      },
      rules: {
        catalogName: [{
          required: true,
          message: '请输入公告内容',
          trigger: 'blur'
        }],
        content: [{
          required: true,
          message: '请输入内容',
          trigger: 'blur'
        }]
      }
    }
  },
  methods: {
    init (bookId, id) {
      this.visible = true
      this.formData = { ...formData, bookId }
      if (id) {
        this.title = '修改数据'
        this.$http.get(`catalog/info/${id}`).then(({ data }) => {
          this.formData = { ...data }
        })
      }
    },
    update () {
      this.$refs.formData.validate(valid => {
        if (valid) {
          if (this.formData.catalogStatus === 2) {
            this.formData.applyTime = ''
          } else {
            if (!this.formData.applyTime) {
              this.formData.applyTime = new Date()
            }
          }
          this.$http.post('catalog/update', this.formData).then(() => {
            this.$alert(`${this.formData.id ? '修改' : '添加'}成功`, { type: 'success' }).then(() => {
              this.visible = false
              this.$emit('onCloseDialog')
            })
          })
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
